{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Image classification multi-label classification\n",
    "\n",
    "1. [Introduction](#Introduction)\n",
    "2. [Prerequisites](#Prequisites)\n",
    "3. [Data Preparation](#Data-Preparation)\n",
    "3. [Multi-label Training](#Multi-label-Training)\n",
    "4. [Inference](#Inference)\n",
    "5. [Clean-up](#Clean-up)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction\n",
    "\n",
    "Welcome to our end-to-end example of multi-label classification using the Sagemaker 1P image classification algorithm. In this demo, we will use the Amazon sagemaker image classification algorithm in transfer learning mode to fine-tune a pre-trained model (trained on imagenet data) to learn to classify a new multi-label dataset. In particular, the pre-trained model will be fine-tuned using [MS-COCO](http://cocodataset.org/#overview) dataset. \n",
    "\n",
    "To get started, we need to set up the environment with a few prerequisite steps, for permissions, configurations, and so on."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Prequisites\n",
    "\n",
    "### Permissions and environment variables\n",
    "\n",
    "Here we set up the linkage and authentication to AWS services. There are three parts to this:\n",
    "\n",
    "* The roles used to give learning and hosting access to your data. This will automatically be obtained from the role used to start the notebook\n",
    "* The S3 bucket that you want to use for training and model data\n",
    "* The Amazon sagemaker image classification docker image which need not be changed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "import sagemaker\n",
    "from sagemaker import get_execution_role\n",
    "\n",
    "role = get_execution_role()\n",
    "print(role)\n",
    "\n",
    "sess = sagemaker.Session()\n",
    "bucket = sess.default_bucket()\n",
    "prefix = 'ic-multilabel'\n",
    "\n",
    "print('using bucket %s'%bucket)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sagemaker.amazon.amazon_estimator import get_image_uri\n",
    "\n",
    "training_image = get_image_uri(sess.boto_region_name, 'image-classification', repo_version=\"latest\")\n",
    "print (training_image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Preparation\n",
    "MS COCO is a large-scale dataset for multiple computer vision tasks, including object detection, segmentation, and captioning. In this notebook, we will use the object detection dataset to construct the multi-label dataset for classification. We will use the 2017 validation set from MS-COCO dataset to train multi-label classifier. MS-COCO dataset consist of images from 80 categories. We will choose 5 categories out of 80 and train the model to learn to classify these 5 categories. These are: \n",
    "\n",
    "1. Person\n",
    "2. Bicycle\n",
    "3. Car\n",
    "4. Motorcycle\n",
    "5. Airplane\n",
    "\n",
    "An image can contain objects of multiple categories. We first create a dataset with these 5 categories. COCO is a very large dataset, and the purpose of this notebook is to show how multi-label classification works. So, instead we’ll take what COCO calls their validation dataset from 2017, and use this as our only data.  We then split this dataset into a train and holdout dataset for fine tuning the model and testing our final accuracy\n",
    "\n",
    "The image classification algorithm can take two types of input formats. The first is a [recordio format](https://mxnet.incubator.apache.org/tutorials/basic/record_io.html) and the other is a [lst format](https://mxnet.incubator.apache.org/how_to/recordio.html?highlight=im2rec). We will use the lst file format for training. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dataset License\n",
    "\n",
    "The annotations in this dataset belong to the COCO Consortium and are licensed under a Creative Commons Attribution 4.0 License. The COCO Consortium does not own the copyright of the images. Use of the images must abide by the Flickr Terms of Use. The users of the images accept full responsibility for the use of the dataset, including but not limited to the use of any copies of copyrighted images that they may create from the dataset. Before you use this data for any other purpose than this example, you should understand the data license, described at http://cocodataset.org/#termsofuse\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import urllib.request\n",
    "\n",
    "def download(url):\n",
    "    filename = url.split(\"/\")[-1]\n",
    "    if not os.path.exists(filename):\n",
    "        urllib.request.urlretrieve(url, filename)\n",
    "\n",
    "\n",
    "# MSCOCO validation image files\n",
    "download('http://images.cocodataset.org/zips/val2017.zip')\n",
    "download('http://images.cocodataset.org/annotations/annotations_trainval2017.zip')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "unzip -qo val2017.zip\n",
    "unzip -qo annotations_trainval2017.zip"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Install tools\n",
    "\n",
    "We need pycocotools to parse the annotations for the MSCOCO dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%%bash\n",
    "pip -q install pycocotools"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Parse the annotation to create lst file\n",
    "Use pycocotools to parse the annotation and create the lst file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pycocotools.coco import COCO\n",
    "import numpy as np\n",
    "import os\n",
    "\n",
    "annFile='./annotations/instances_val2017.json'\n",
    "coco=COCO(annFile)\n",
    "\n",
    "catIds = coco.getCatIds()\n",
    "image_ids_of_cats = []\n",
    "for cat in catIds:\n",
    "    image_ids_of_cats.append(coco.getImgIds(catIds=cat))\n",
    "\n",
    "image_ids = []\n",
    "labels = []\n",
    "# use only the first 5 classes\n",
    "# obtain image ids and labels for images with these 5 classes\n",
    "cats = [1, 2, 3, 4, 5]\n",
    "for ind_cat in cats:\n",
    "    for image_id in image_ids_of_cats[ind_cat-1]:\n",
    "        if image_id in image_ids:\n",
    "            labels[image_ids.index(image_id)][ind_cat-1] = 1\n",
    "        else:\n",
    "            image_ids.append(image_id)\n",
    "            labels.append(np.zeros(len(cats), dtype=np.int))\n",
    "            labels[-1][ind_cat-1] = 1\n",
    "# Construct the lst file from the image ids and labels\n",
    "# The first column is the image index, the last is the image filename\n",
    "# and the second to last but one are the labels\n",
    "with open('image.lst', 'w') as fp:\n",
    "    sum_labels = labels[0]\n",
    "    for ind, image_id in enumerate(image_ids):\n",
    "        coco_img = coco.loadImgs(image_id)\n",
    "        image_path = os.path.join(coco_img[0]['file_name'])\n",
    "        label_h = labels[ind]\n",
    "        sum_labels += label_h\n",
    "        fp.write(str(ind) + '\\t')\n",
    "        for j in label_h:\n",
    "            fp.write(str(j) + '\\t')\n",
    "        fp.write(image_path)\n",
    "        fp.write('\\n')\n",
    "    fp.close()\n",
    "print(sum_labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create training and validation set\n",
    "Create training and validation set by splitting the lst file. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "shuf image.lst > im.lst\n",
    "head -n 2500 im.lst > mscocoval2017train.lst\n",
    "tail -n +2501 im.lst > mscocoval2017val.lst\n",
    "head mscocoval2017train.lst\n",
    "wc -l mscocoval2017train.lst\n",
    "wc -l mscocoval2017val.lst"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Upload the data\n",
    "Upload the data onto the s3 bucket. The images are uploaded onto train and validation bucket. The lst files are uploaded to train_lst and validation_lst folders. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Four channels: train, validation, train_lst, and validation_lst\n",
    "s3train = 's3://{}/{}/train/'.format(bucket, prefix)\n",
    "s3validation = 's3://{}/{}/validation/'.format(bucket, prefix)\n",
    "s3train_lst = 's3://{}/{}/train_lst/'.format(bucket, prefix)\n",
    "s3validation_lst = 's3://{}/{}/validation_lst/'.format(bucket, prefix)\n",
    "\n",
    "# upload the image files to train and validation channels\n",
    "!aws s3 cp val2017 $s3train --recursive --quiet\n",
    "!aws s3 cp val2017 $s3validation --recursive --quiet\n",
    "\n",
    "# upload the lst files to train_lst and validation_lst channels\n",
    "!aws s3 cp mscocoval2017train.lst $s3train_lst --quiet\n",
    "!aws s3 cp mscocoval2017val.lst $s3validation_lst --quiet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Multi-label Training\n",
    "Now that we are done with all the setup that is needed, we are ready to train our object detector. To begin, let us create a ``sageMaker.estimator.Estimator`` object. This estimator will launch the training job.\n",
    "\n",
    "### Training parameters\n",
    "There are two kinds of parameters that need to be set for training. The first one are the parameters for the training job. These include:\n",
    "\n",
    "* **Training instance count**: This is the number of instances on which to run the training. When the number of instances is greater than one, then the image classification algorithm will run in distributed settings. \n",
    "* **Training instance type**: This indicates the type of machine on which to run the training. Typically, we use GPU instances for these training \n",
    "* **Output path**: This the s3 folder in which the training output is stored"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s3_output_location = 's3://{}/{}/output'.format(bucket, prefix)\n",
    "multilabel_ic = sagemaker.estimator.Estimator(training_image,\n",
    "                                         role, \n",
    "                                         train_instance_count=1, \n",
    "                                         train_instance_type='ml.p2.xlarge',\n",
    "                                         train_volume_size = 50,\n",
    "                                         train_max_run = 360000,\n",
    "                                         input_mode= 'File',\n",
    "                                         output_path=s3_output_location,\n",
    "                                         sagemaker_session=sess)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Algorithm parameters\n",
    "\n",
    "Apart from the above set of parameters, there are hyperparameters that are specific to the algorithm. These are:\n",
    "\n",
    "* **num_layers**: The number of layers (depth) for the network. We use 18 in this samples but other values such as 50, 152 can be used.\n",
    "* **use_pretrained_model**: Set to 1 to use pretrained model for transfer learning.\n",
    "* **image_shape**: The input image dimensions,'num_channels, height, width', for the network. It should be no larger than the actual image size. The number of channels should be same as the actual image.\n",
    "* **num_classes**: This is the number of output classes for the dataset. We use 5 classes from MSCOCO and hence it is set to 5\n",
    "* **mini_batch_size**: The number of training samples used for each mini batch. In distributed training, the number of training samples used per batch will be N * mini_batch_size where N is the number of hosts on which training is run\n",
    "* **resize**: Resize the image before using it for training. The images are resized so that the shortest side is of this parameter. If the parameter is not set, then the training data is used as such without resizing.\n",
    "* **epochs**: Number of training epochs\n",
    "* **learning_rate**: Learning rate for training\n",
    "* **num_training_samples**: This is the total number of training samples. It is set to 2500 for COCO dataset with the current split\n",
    "* **use_weighted_loss**: This parameter is used to balance the influence of the positive and negative samples within the dataset.\n",
    "* **augmentation_type**: This parameter determines the type of augmentation used for training. It can take on three values, 'crop', 'crop_color' and 'crop_color_transform'\n",
    "* **precision_dtype**: The data type precision used during training. Using ``float16`` can lead to faster training with minimal drop in accuracy, paritcularly on P3 machines. By default, the parameter is set to ``float32``\n",
    "* **multi_label**: Set multi_label to 1 for multi-label processing\n",
    "\n",
    "You can find a detailed description of all the algorithm parameters at https://docs.aws.amazon.com/sagemaker/latest/dg/IC-Hyperparameter.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "multilabel_ic.set_hyperparameters(num_layers=18,\n",
    "                             use_pretrained_model=1,\n",
    "                             image_shape = \"3,224,224\",\n",
    "                             num_classes=5,\n",
    "                             mini_batch_size=128,\n",
    "                             resize=256,\n",
    "                             epochs=5,\n",
    "                             learning_rate=0.001,\n",
    "                             num_training_samples=2500,\n",
    "                             use_weighted_loss=1,\n",
    "                             augmentation_type = 'crop_color_transform',\n",
    "                             precision_dtype='float32',\n",
    "                             multi_label=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Input data specification\n",
    "Set the data type and channels used for training. In this training, we use application/x-image content type that require individual images and lst file for data input. In addition, Sagemaker image classification algorithm supports application/x-recordio format which can be used for larger datasets. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data = sagemaker.session.s3_input(s3train, distribution='FullyReplicated', \n",
    "                        content_type='application/x-image', s3_data_type='S3Prefix')\n",
    "validation_data = sagemaker.session.s3_input(s3validation, distribution='FullyReplicated', \n",
    "                             content_type='application/x-image', s3_data_type='S3Prefix')\n",
    "train_data_lst = sagemaker.session.s3_input(s3train_lst, distribution='FullyReplicated', \n",
    "                        content_type='application/x-image', s3_data_type='S3Prefix')\n",
    "validation_data_lst = sagemaker.session.s3_input(s3validation_lst, distribution='FullyReplicated', \n",
    "                             content_type='application/x-image', s3_data_type='S3Prefix')\n",
    "data_channels = {'train': train_data, 'validation': validation_data, 'train_lst': train_data_lst, \n",
    "                 'validation_lst': validation_data_lst}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Start the training\n",
    "Start training by calling the fit method in the estimator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "multilabel_ic.fit(inputs=data_channels, logs=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Inference\n",
    "\n",
    "***\n",
    "\n",
    "A trained model does nothing on its own. We now want to use the model to perform inference. For this example, that means predicting the class of the image. You can deploy the created model by using the deploy method in the estimator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ic_classifier = multilabel_ic.deploy(initial_instance_count = 1,\n",
    "                                          instance_type = 'ml.m4.xlarge')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download test image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline  \n",
    "!wget -q -O /tmp/test.jpg https://images.pexels.com/photos/763398/pexels-photo-763398.jpeg\n",
    "    \n",
    "import cv2\n",
    "# resize image size for inference\n",
    "file_name = '/tmp/test.jpg'\n",
    "im = cv2.imread(file_name)\n",
    "im = cv2.resize(im, (600, 400))\n",
    "cv2.imwrite(file_name, im)\n",
    "\n",
    "# display test image\n",
    "from IPython.display import Image, display\n",
    "img = Image(file_name) \n",
    "display(img)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Evaluation\n",
    "\n",
    "Evaluate the image through the network for inference. The network outputs class probabilities for all the classes. As can be seen from this example, the network output is pretty good even with training for only 5 epochs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "with open(file_name, 'rb') as image:\n",
    "    f = image.read()\n",
    "    b = bytearray(f)\n",
    "ic_classifier.content_type = 'application/x-image'\n",
    "results = ic_classifier.predict(b)\n",
    "prob = json.loads(results)\n",
    "classes = ['Person', 'Bicycle', 'Car', 'Motorcycle', 'Airplane']\n",
    "for idx, val in enumerate(classes):\n",
    "    print('%s:%f '%(classes[idx], prob[idx]), end='')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Clean up\n",
    "You can use the following command to delete the endpoint. The endpoint that is created above is persistent and would consume resources till it is deleted. It is good to delete the endpoint when it is not used"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ic_classifier.delete_endpoint()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conda_mxnet_p36",
   "language": "python",
   "name": "conda_mxnet_p36"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  },
  "notice": "Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.  Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License."
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
